package logic

import (
	"context"

	"go-weixin/app/guitar/rpc/internal/svc"
	"go-weixin/app/guitar/rpc/pb/proto/guitar"

	"go-weixin/app/guitar/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/x/errors"
)

type GuitarQueryLikeOneFieldLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGuitarQueryLikeOneFieldLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GuitarQueryLikeOneFieldLogic {
	return &GuitarQueryLikeOneFieldLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GuitarQueryLikeOneFieldLogic) GuitarQueryLikeOneField(in *guitar.GuitarQueryLikeOneFieldReq) (*guitar.GuitarQueryLikeOneFieldResp, error) {
	limit := 10
	offset := 10 * (in.Page - 1)
	var gm []model.GuitarJoinImageGroup
	q := l.svcCtx.ChenDb.Join("LEFT", "guitar_image", "guitar.id = guitar_image.guitar_id")
	switch in.Field {
	case "id":
		q.Where("guitar."+in.Field+" = ?", in.Query)
	case "title":
		q.Where("guitar."+in.Field+" LIKE ?", "%"+in.Query+"%")
	case "create_at":
		q.Where("Date(guitar."+in.Field+") = ?", in.Query)
	}

	err := q.Limit(limit, int(offset)).Find(&gm)
	if err != nil {
		return nil, errors.New(8000, "mysql.query.like.file:"+err.Error())
	}
	var guitarImage []*guitar.GuitarJoinImageBase
	if len(gm) > 0 {
		var index int
		idSet := make(map[int]int, len(gm))
		for i := 0; i < len(gm); i++ {
			if v, ok := idSet[int(gm[i].GuitarModel.Id)]; ok {
				index = v
			} else {
				index = i
				idSet[int(gm[i].GuitarModel.Id)] = i
				guitarImage = append(guitarImage, &guitar.GuitarJoinImageBase{
					Id:    gm[i].GuitarModel.Id,
					Title: gm[i].GuitarModel.Title,
				})
			}

			guitarImage[index].ImageList = append(guitarImage[index].ImageList, &guitar.GuitarImageBase{
				Id:       gm[i].GuitarImageModel.Id,
				Url:      gm[i].GuitarImageModel.Url,
				GuitarId: gm[i].GuitarImageModel.GuitarId,
			})
		}
	}

	return &guitar.GuitarQueryLikeOneFieldResp{QueryData: guitarImage}, nil
}
